package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    //上传文件到oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        String url = "";
        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            //获取上传文件流
            InputStream inputStream = file.getInputStream();
            //在文件名中添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String fileName  = file.getOriginalFilename();
            fileName = uuid+fileName;
            //把文件按照日期进行分类2019/11/12/1.jpg
            String datepath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            fileName = datepath+"/"+fileName;
            //文件上传至阿里云第二个参数对象 上传到oss文件路径和文件名称
            ossClient.putObject(bucketName, fileName, inputStream);
            //把上传之后文件的路径返回
            //https://jiangzhijie.oss-cn-beijing.aliyuncs.com/p1.jpg
            url="https://"+bucketName+"."+endPoint+"/"+fileName;
            // 关闭OSSClient
            ossClient.shutdown();
        } catch (IOException  e) {
          e.printStackTrace();
        }
        return url;
    }
}
